package com.zdd.ehe.interceptor;

import com.alibaba.fastjson.JSON;
import com.zdd.ehe.result.Result;
import com.zdd.ehe.util.JwtUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @title:JwtValidateInterceptor
 * @author:ZhuiZhu
 * @description:Jwt拦截器
 * @createDate: 2023/3/12  20:00
 */
@Component
@Slf4j
public class JwtValidateInterceptor implements HandlerInterceptor {
    @Autowired
    private JwtUtil jwtUtil;


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 获取token
        String token = request.getHeader("token");
        log.debug(request.getRequestURI() + "需要验证: " + token );
        if(token != null){
            try {
                // 若token有问题则会抛出异常
                jwtUtil.parseToken(token);
                log.debug(request.getRequestURI() + "验证通过");
                return true;
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        log.debug(request.getRequestURI() + "验证失败,禁止访问!");
        response.setContentType("application/json;charset=utf-8");
        Result result = Result.error(400,"jwt无效，请重新登录");
        response.getWriter().write(JSON.toJSONString(result));
        return false; //拦截
    }


}
